<template>
  <div class="form-container">
    <el-form ref="ruleFormRef" :model="form" :rules="rules" style="max-width: 800px; margin: auto;">
      <el-row :class="{ disableClss: props.isPreview }">
        <!-- 基本信息区域 -->
        <el-col :span="24">
          <div class="form-section-title">基本信息</div>
        </el-col>

        <!-- 学生学号 + 姓名 -->
        <el-col :span="12">
          <el-form-item label="学生学号" prop="studentId">
            <el-select
                v-model="form.studentId"
                placeholder="请选择学生学号"
                filterable
                style="width: 100%"
                @change="fillStudentName"
                :disabled="props.isPreview"
            >
              <el-option
                  v-for="item in studentList"
                  :key="item.id"
                  :label="`${item.studentId}-${item.studentName}`"
                  :value="item.studentId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="学生姓名" prop="studentName">
            <el-input
                v-model="form.studentName"
                placeholder="请输入学生姓名"
                :disabled="true"
                class="bg-gray-100"
            />
          </el-form-item>
        </el-col>

        <!-- 原学籍状态 + 异动类型 -->
        <el-col :span="12">
          <el-form-item label="原学籍状态" prop="originalStatus">
            <el-input
                v-model="form.originalStatus"
                placeholder="请输入原学籍状态"
                :disabled="props.isPreview"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="异动类型" prop="changeType">
            <el-input
                v-model="form.changeType"
                placeholder="请输入异动类型"
                :disabled="props.isPreview"
            />
          </el-form-item>
        </el-col>

        <!-- 异动申请原因 -->
        <el-col :span="24">
          <el-form-item label="异动申请原因" prop="changeReason">
            <el-input
                v-model="form.changeReason"
                type="textarea"
                placeholder="请输入异动申请原因"
                :autosize="{ minRows: 3, maxRows: 3 }"
                style="width: 100%"
                :disabled="props.isPreview"
            />
          </el-form-item>
        </el-col>

        <!-- 申请日期 + 材料审核状态 -->
        <el-col :span="12">
          <el-form-item label="申请提交日期" prop="applyDate">
            <el-date-picker
                v-model="form.applyDate"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择申请提交日期"
                style="width: 100%"
                :disabled="props.isPreview"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="材料审核状态" prop="materialsStatus">
            <el-input
                v-model="form.materialsStatus"
                placeholder="请输入材料审核状态"
                :disabled="props.isPreview"
            />
          </el-form-item>
        </el-col>

        <!-- 申请材料清单 -->
        <el-col :span="24">
          <el-form-item label="申请材料清单" prop="applyMaterials">
            <el-input
                v-model="form.applyMaterials"
                type="textarea"
                placeholder="请输入申请材料清单"
                :autosize="{ minRows: 3, maxRows: 3 }"
                style="width: 100%"
                :disabled="props.isPreview"
            />
          </el-form-item>
        </el-col>

        <!-- 审核信息区域 -->
        <el-col :span="24" style="margin-top: 15px;">
          <div class="form-section-title">审核信息</div>
        </el-col>

        <!-- 一级审核 -->
        <el-col :span="24">
          <div class="audit-level-title">一级审核</div>
        </el-col>
        <el-col :span="12">
          <el-form-item label="审核人" prop="reviewer1">
            <el-input
                v-model="form.reviewer1"
                placeholder="请输入一级审核人"
                :disabled="props.isPreview"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="审核结果" prop="reviewer1Result">
            <el-input
                v-model="form.reviewer1Result"
                placeholder="请输入一级审核结果"
                :disabled="props.isPreview"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="审核时间" prop="reviewer1Time">
            <el-date-picker
                v-model="form.reviewer1Time"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择一级审核时间"
                style="width: 100%"
                :disabled="props.isPreview"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="审核意见" prop="reviewer1Opinion">
            <el-input
                v-model="form.reviewer1Opinion"
                type="textarea"
                placeholder="请输入一级审核意见"
                :autosize="{ minRows: 2, maxRows: 2 }"
                style="width: 100%"
                :disabled="props.isPreview"
            />
          </el-form-item>
        </el-col>

        <!-- 二级审核 -->
        <el-col :span="24">
          <div class="audit-level-title">二级审核</div>
        </el-col>
        <el-col :span="12">
          <el-form-item label="审核人" prop="reviewer2">
            <el-input
                v-model="form.reviewer2"
                placeholder="请输入二级审核人"
                :disabled="props.isPreview"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="审核结果" prop="reviewer2Result">
            <el-input
                v-model="form.reviewer2Result"
                placeholder="请输入二级审核结果"
                :disabled="props.isPreview"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="审核时间" prop="reviewer2Time">
            <el-date-picker
                v-model="form.reviewer2Time"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择二级审核时间"
                style="width: 100%"
                :disabled="props.isPreview"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="审核意见" prop="reviewer2Opinion">
            <el-input
                v-model="form.reviewer2Opinion"
                type="textarea"
                placeholder="请输入二级审核意见"
                :autosize="{ minRows: 2, maxRows: 2 }"
                style="width: 100%"
                :disabled="props.isPreview"
            />
          </el-form-item>
        </el-col>

        <!-- 三级审核 -->
        <el-col :span="24">
          <div class="audit-level-title">三级审核</div>
        </el-col>
        <el-col :span="12">
          <el-form-item label="审核人" prop="reviewer3">
            <el-input
                v-model="form.reviewer3"
                placeholder="请输入三级审核人"
                :disabled="props.isPreview"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="最终结果" prop="reviewer3Result">
            <el-input
                v-model="form.reviewer3Result"
                placeholder="请输入最终审核结果"
                :disabled="props.isPreview"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="审核时间" prop="reviewer3Time">
            <el-date-picker
                v-model="form.reviewer3Time"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择三级审核时间"
                style="width: 100%"
                :disabled="props.isPreview"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="审核意见" prop="reviewer3Opinion">
            <el-input
                v-model="form.reviewer3Opinion"
                type="textarea"
                placeholder="请输入三级审核意见"
                :autosize="{ minRows: 2, maxRows: 2 }"
                style="width: 100%"
                :disabled="props.isPreview"
            />
          </el-form-item>
        </el-col>

        <!-- 最终学籍状态 + 备注 -->
        <el-col :span="24">
          <el-form-item label="最终学籍状态" prop="finalStatus">
            <el-input
                v-model="form.finalStatus"
                placeholder="请输入最终学籍状态"
                :disabled="props.isPreview"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注信息" prop="remark">
            <el-input
                v-model="form.remark"
                type="textarea"
                placeholder="请输入备注信息"
                :autosize="{ minRows: 3, maxRows: 3 }"
                style="width: 100%"
                :disabled="props.isPreview"
            />
          </el-form-item>
        </el-col>

        <!-- 提交按钮 -->
        <el-col :span="24" v-if="!props.isPreview && props.showSubmit">
          <el-form-item>
            <el-button type="primary" @click="handleSubmit">提交</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 审批人选择组件 -->
    <TagApproveSelect
        v-if="hasChooseApprove == 'true'"
        v-model:formCode="formCode"
        @chooseApprove="chooseApprovers"
    />
  </div>
</template>

<script setup>
// 1. 仅导入必需依赖（对齐正常表单，避免多余导入）
import { ref, reactive, getCurrentInstance} from 'vue';
import { listStudentManger } from "@/api/student/studentManger.js";
import TagApproveSelect from "@/components/BizSelects/TagApproveSelect/index.vue";

// 2. 框架核心：获取proxy和路由参数（完全对齐正常表单）
const { proxy } = getCurrentInstance();
const route = useRoute();
const formCode = route.query?.formCode ?? '';
const hasChooseApprove = route.query?.hasChooseApprove ?? 'false';

// 3. 组件传参：完全对齐正常表单的极简写法
let props = defineProps({
  previewData: {
    type: Object,
    default: () => ({}),
  },
  showSubmit: {
    type: Boolean,
    default: false,
  },
  isPreview: {
    type: Boolean,
    default: true,
  }
});

// 4. 表单核心：对齐正常表单的初始化逻辑（简洁，无多余处理）
const ruleFormRef = ref(null);
const studentList = ref([]); // 仅保留业务必需的列表数据

// 4.1 表单数据初始化：从previewData解构，新增自选审批人字段（业务必需）
const {
  studentId,
  studentName,
  originalStatus,
  changeType,
  changeReason,
  applyDate,
  applyMaterials,
  materialsStatus,
  reviewer1,
  reviewer1Opinion,
  reviewer1Time,
  reviewer1Result,
  reviewer2,
  reviewer2Opinion,
  reviewer2Time,
  reviewer2Result,
  reviewer3,
  reviewer3Opinion,
  reviewer3Time,
  reviewer3Result,
  finalStatus,
  remark
} = props.previewData;

// 4.2  reactive初始化：仅包含解构字段 + 自选审批人字段（无多余字段）
const form = reactive({
  studentId,
  studentName,
  originalStatus,
  changeType,
  changeReason,
  applyDate,
  applyMaterials,
  materialsStatus,
  reviewer1,
  reviewer1Opinion,
  reviewer1Time,
  reviewer1Result,
  reviewer2,
  reviewer2Opinion,
  reviewer2Time,
  reviewer2Result,
  reviewer3,
  reviewer3Opinion,
  reviewer3Time,
  reviewer3Result,
  finalStatus,
  remark,
});

// 5. 表单验证规则：对齐正常表单的简洁写法（仅保留必需规则）
let rules = {
  studentId: [{
    required: true,
    message: '请选择学生学号',
    trigger: ['blur', 'change']
  }],
  studentName: [{
    required: true,
    message: '学生姓名不能为空',
    trigger: 'blur'
  }],
  changeType: [{
    required: true,
    message: '请输入异动类型',
    trigger: 'blur'
  }],
  changeReason: [{
    required: true,
    message: '请输入异动申请原因',
    trigger: 'blur'
  }],
  applyDate: [{
    required: true,
    message: '请选择申请提交日期',
    trigger: 'change'
  }]
};

// 6. 业务逻辑：加载学生列表（对齐正常表单无多余逻辑，错误提示用框架$modal）
const loadStudentList = () => {
  // 6.1 接口传参：按框架接口规范传分页参数（避免空参数导致接口报错）
  listStudentManger({ pageNum: 1, pageSize: 10000 }).then(response => {
    if (response.rows) studentList.value = response.rows;
  }).catch(error => {
    // 6.2 错误提示：用框架全局$modal（对齐正常表单，避免用ElMessage）
    proxy.$modal.msgError('加载学生列表失败：' + error.message);
  });
};

// 7. 辅助逻辑：选择学号填充姓名（简洁，无多余判断）
const fillStudentName = () => {
  const student = studentList.value.find(item => item.studentId === form.studentId);
  form.studentName = student ? student.studentName : '';
};

// 8. 自选审批人：对齐正常表单的极简写法
const chooseApprovers = (data) => {
  form.approversList = data.approvers;
  form.approversValid = data.nodeVaild;
};

// 9. 框架要求：getFromData（完全对齐正常表单，直接stringify）
const getFromData = () => {
  return new Promise((resolve, reject) => {
    try {
      resolve(JSON.stringify(form)); // 去掉深拷贝，避免格式异常
    } catch (error) {
      reject(error);
    }
  });
};

// 10. 提交逻辑：完全对齐正常表单的链式调用（无async/await，避免多余处理）
const handleSubmit = () => {
  handleValidate().then((isValid) => {
    if (isValid) {
      proxy.$emit("handleBizBtn", JSON.stringify(form));
    }
  });
};

// 11. 表单验证：完全对齐正常表单的写法（用$modal提示，无Promise额外包装）
const handleValidate = () => {
  return proxy.$refs['ruleFormRef'].validate((valid) => {
    if (!valid) {
      return Promise.reject(false);
    }
    // 自选审批人校验：对齐正常表单的判断逻辑
    if (hasChooseApprove == 'true') {
      if (!form.approversValid) {
        proxy.$modal.msgError('请选择自选审批人');
        return Promise.reject(false);
      }
    }
    return Promise.resolve(true);
  });
};

// 12. 暴露方法：完全对齐正常表单（仅暴露框架必需的2个方法）
defineExpose({
  handleValidate,
  getFromData
});
// 13. 初始化加载：仅调用接口，无多余逻辑
loadStudentList()
</script>

<style scoped lang="scss">
// 样式：对齐正常表单的简洁写法（去掉多余box-shadow等，避免冲突）
.disableClss {
  pointer-events: none;
}

.form-container {
  background: white !important;
  padding: 10px;
  max-width: 750px;
  min-height: 95%;
  left: 0;
  bottom: 0;
  right: 0;
  margin: auto;
}

// 保留业务必需的标题样式，简化命名
.form-section-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin: 10px 0;
  padding-bottom: 5px;
  border-bottom: 1px solid #ebeef5;
}

.audit-level-title {
  font-size: 14px;
  font-weight: 500;
  color: #606266;
  margin: 10px 0;
  padding-left: 5px;
  border-left: 3px solid #1890ff;
}

.bg-gray-100 {
  background-color: #f5f7fa;
}
</style>